package be.novelfaces.test.common;

import javax.faces.component.UIViewRoot;

import org.jboss.test.faces.mock.MockFacesEnvironment;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;

import be.novelfaces.component.util.RenderUtils;
import be.novelfaces.component.util.RenderUtilsFactoryForTests;

public class MockFacesEnvironmentRule extends TestWatcher {

	private MockFacesEnvironment environment = MockFacesEnvironment
			.createEnvironment();
	private RenderUtils renderUtilsMock;
	private UIViewRoot uiViewRootMock;

	@Override
	protected void starting(Description description) {
		renderUtilsMock = RenderUtilsFactoryForTests
				.setMockAsInstance(environment);
		uiViewRootMock = getEnvironment().createMock(UIViewRoot.class);

	}
	
	@Override
	protected void finished(Description description) {
		// do verification for mocked objects
		environment.verify();

		// do clean up
		environment.release();
		environment = null;
		RenderUtilsFactoryForTests.resetInstance();
		uiViewRootMock = null;
	}

	public MockFacesEnvironmentRule withUIViewRootMock() {
		uiViewRootMock = getEnvironment().createMock(UIViewRoot.class);
		return this;
	}

	public MockFacesEnvironment getEnvironment() {
		return environment;
	}

	public RenderUtils getRenderUtilsMock() {
		return renderUtilsMock;
	}

	public UIViewRoot getUiViewRootMock() {
		return uiViewRootMock;
	}

}
